﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Xml;

namespace Utilities
{
    public class XmlUtil
    {
        public static T Deserialize<T>(string xmlObj)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xmlObj)))
            {
                XmlTextReader tr = new XmlTextReader(ms);
                if (serializer.CanDeserialize(tr))
                {
                    return (T)serializer.Deserialize(ms);
                }
            }
            return default(T);
        }

        public static string Serialize<T>(T obj)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream())
            {
                XmlTextWriter tw = new XmlTextWriter(ms,Encoding.UTF8);
                serializer.Serialize(tw, obj);
                return Encoding.UTF8.GetString(ms.ToArray());
            }
        }
    }
}
